/*
    Project:        Home Power Control
    File:           HPCAnemometer.cpp
    Author:         christian@karunamusic.at
    Date:           11.2014
    Description:    Sensor to measure the speed of wind.
                    The sensor gives one tick per rotation.
                    One tick per second means a wind speed of 2,4km/h.
 */

#include <iostream>
#include <wiringPi.h>
#include <boost/thread/mutex.hpp>
#include "globals.h"
#include "HPCAnemometer.h"

using namespace std;

unsigned int HPCAnemometer::m_Counter = 0;
boost::mutex amtx;

HPCAnemometer::HPCAnemometer( unsigned long id, unsigned int pin, unsigned int interval )
    : HPCThreadedSensor( id, pin, interval )
{
    PROFILE_THIS;

    m_Old = 0.0f;
    digitalWrite( m_Pin, HIGH );
    wiringPiISR( m_Pin, INT_EDGE_FALLING, &isr );
}

HPCAnemometer::~HPCAnemometer()
{
    PROFILE_THIS;
}

void HPCAnemometer::isr()
{
    PROFILE_THIS;

    amtx.lock();
    m_Counter++;
    amtx.unlock();
}

void HPCAnemometer::Measure()
{
    PROFILE_THIS;

    // 1 tick == 2.4km/h
    float v = ((m_Counter * 24.0f) / 10.0f) / m_Time;
    float scale = 0.1f;
    v = floor(v / scale + 0.5f) * scale;

    m_Value = v;
}

bool HPCAnemometer::hasChanged()
{
    PROFILE_THIS;

    Measure();
    LOG( debug, "Measured value: " << (string)m_Value << " " << MeasureUnit() );

    amtx.lock();
    m_Counter = 0;
    amtx.unlock();

    return (m_Value != m_Old);
}

int HPCAnemometer::isAlarm()
{
    unsigned int tmp = m_Counter;
    unsigned int mTime = 2;

    sleep(mTime); // count ticks for at least 1sec !

    tmp = m_Counter - tmp; // get the ticks of the last mTime seconds.

    m_Value = (((float)m_Counter * 24.0f) / 10.0f) / (float)mTime;
    float scale = 0.1;
    m_Value = floor( ( float )m_Value / scale + 0.5f ) * scale;

    return m_Value.isAlarm();
}

unsigned int HPCAnemometer::Beaufort() const
{
    PROFILE_THIS;

    int ret;
    float fl = m_Value;
    if ( fl <= 2.0 )
    {
        ret = 0;
    }
    else if ( fl >  2.0 && fl <=  5.0 )
    {
        ret = 1;
    }
    else if ( fl >  5.0 && fl <= 11.0 )
    {
        ret = 2;
    }
    else if ( fl > 11.0 && fl <= 19.0 )
    {
        ret = 3;
    }
    else if ( fl > 19.0 && fl <= 28.0 )
    {
        ret = 4;
    }
    else if ( fl > 28.0 && fl <= 38.0 )
    {
        ret = 5;
    }
    else if ( fl > 38.0 && fl <= 49.0 )
    {
        ret = 6;
    }
    else if ( fl > 49.0 && fl <= 61.0 )
    {
        ret = 7;
    }
    else if ( fl > 61.0 && fl <= 74.0 )
    {
        ret = 8;
    }
    else if ( fl > 74.0 && fl <= 89.0 )
    {
        ret = 9;
    }
    else if ( fl > 89.0 && fl <= 102.0 )
    {
        ret = 10;
    }
    else if ( fl > 102.0 && fl <= 117.0 )
    {
        ret = 11;
    }
    else
    {
        ret = 12;
    }

    return ret;
}
